<template>
	<div class="message-box">
		<div class="content" ref="messageBoxContent"></div>
	</div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { useRootStore } from '@v/store';
import { createMessageItem } from './messageItem';

const store = useRootStore();

const messageBoxContent = ref();

// 更新消息方法
let fn: Function;
function updateMessageItem() {
	fn && fn();

	if (store.message.latest) {
		fn = createMessageItem(messageBoxContent.value as HTMLDivElement);
	}
}

// 实时更新消息
watch(
	() => store.message.latest,
	(_s, v) => {
		const s1 = v?.id !== store.message.list[store.message.list.length - 1]?.id;

		if (s1 || !v) updateMessageItem();
	},
	{ deep: true }
);

// 监听消息列表为空时清除 message box
watch(store.message.list, (v) => {
	if (v.length === 0) {
		fn && fn();
	}
});

onMounted(() => {
	updateMessageItem();
});

/* let megid = 0;
window.addEventListener('keydown', async (event) => {
	console.log(event.key);

	if (event.key === ',') {
		console.log('inset');

		megid = await store.addMessage('insert', 'info', 'a' + Math.random());
	} else if (event.key === '.') {
		console.log('update');

		store.setMessage('update', {
			id: megid,
			type: 'info',
			message: 'a' + Math.random(),
		});
	} else if (event.key === 'Delete') {
		store.message.list.splice(0, store.message.list.length);
	} else if (event.key === '/') {
		await store.addMessage('insert', 'success', 'a' + Math.random());
	}
}); */
</script>

<style scoped lang="scss">
.message-box {
	height: 100%;
	flex-grow: 1;
	position: relative;
	overflow: hidden;
	.content {
		position: absolute;
		left: 0;
		top: 0;
		width: calc(100% - 0px);
		height: 100%;
	}
}
</style>
